package com.ecotope.quartz.module.schedule;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ecotope.quartz.module.entity.AccessData;
import com.ecotope.quartz.module.entity.AtmosphericStation;
import com.ecotope.quartz.module.opentsdb.ExpectResponse;
import com.ecotope.quartz.module.opentsdb.HttpClientImpl;
import com.ecotope.quartz.module.opentsdb.builder.MetricBuilder;
import com.ecotope.quartz.module.opentsdb.response.Response;
import com.ecotope.quartz.module.service.AccessDataService;
import com.ecotope.quartz.module.service.AtmosphericStationService;
import com.ecotope.quartz.module.service.TownAtmosphericStationService;
import com.ecotope.quartz.module.util.DateUtil;
import com.ecotope.quartz.module.util.HttpURLConnectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
@EnableAsync
@EnableScheduling
@SuppressWarnings("all")
public class DayAtmosphereSchedule {

    //省平台地址
    private String baseUrl = "http://59.202.42.88:8180/sjmh/dynamicservice/dynamicquery";

    //大气乡镇
    private final static String getDataQTownByxzqh = "http://10.33.70.133:6081/rest/api/foreign/getDataQTown";

    //页大小
    private Integer pageSize = 10000;

    //页码
    private Integer pageNum = 1;

    //站点日数据
    private String fwxhZdr = "cce8b2a4fad848e89d3ece8b0f5ead1f";
    private String keyZdr = "a5894620-0a1b-4c85-8c71-4e51552cc379";

    //城市日数据
    private String fwxhCsr = "7c81f7c2807546bd9e74438b76c8555a";
    private String keyCsr = "196f7a33-6988-4353-97b9-531f82b2ca5b";

    //清新日数据
    private String fwxhQxr = "3be112c86cd44e45abd70c655ae3b63e";
    private String keyQxr = "1c51a412-bba2-4abb-ab8f-d45190945d5e";


    @Autowired
    private AtmosphericStationService atmosphericStationService;

    @Autowired
    private AccessDataService accessDataService;

    @Autowired
    private TownAtmosphericStationService townAtmosphericStationService;

    /**
     * ZD 空气站点日数据 （每日执行）
     */
    @Scheduled(cron = "0 23 0 */1 * ?")
    @Async
    public void getZDDayDateInsertOpentsdb() {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String JSSJ = df.format(date);

        Date dateNew = date;
        Calendar calendarNew = Calendar.getInstance();
        calendarNew.setTime(dateNew);
        calendarNew.add(Calendar.DATE, -2);
        dateNew = calendarNew.getTime();
        String KSSJ = df.format(dateNew);

        HttpClientImpl client = new HttpClientImpl("http://61.164.218.155:61242");
        try {
            String kssj = URLEncoder.encode(KSSJ, "utf-8");
            String jssj = URLEncoder.encode(JSSJ, "utf-8");
            String url = baseUrl + "?fwxh=" + fwxhZdr + "&key=" + keyZdr + "&pagenum=" + pageNum + "&pageSize=" + pageSize + "&KSSJ=" + kssj + "&JSSJ=" + jssj;
            String methodReturn = HttpURLConnectionUtil.getMethod(url);
            if (HttpURLConnectionUtil.isJsonObject(methodReturn)) {
                JSONObject jsonObject = JSONObject.parseObject(methodReturn);
                JSONObject data = jsonObject.getJSONObject("data");
                String kqzlzdrsj = data.getString("KQZLZDRSJ");

                if (kqzlzdrsj != null && !kqzlzdrsj.equals("[]")) {
                    //mysql数据库 记录数据插入时间
                    AccessData accessData = AccessData.builder().type(1).url("每日数据===>" + KSSJ + "--" + JSSJ).data("空气站点").build();
                    accessDataService.insert(accessData);
                    log.info("insert ZD-data-opentsdb start:");
                    //插入opentsdb
                    JSONArray jsonArray = JSONArray.parseArray(kqzlzdrsj);
                    for (Object o : jsonArray) {
                        Map map = JSONObject.parseObject(o.toString(), Map.class);
                        if (map.size() > 0) {
                            //移除不必要的数据
                            map.remove("CJSJ");
                            map.remove("PXH");
                            map.remove("BZ");
                            map.remove("ZDMC");
                            map.remove("XGSJ");
                            map.remove("XH");
                            //空气质量指数级别
                            DateUtil.KQZLZSJBMap(map);
                            //空气质量颜色
                            DateUtil.KQZLYSMap(map);
                            //空气质量类别
                            DateUtil.KQZLLBMap(map);
                            //首要污染物
                            DateUtil.SYWRWMap(map);
                            //转换时间戳
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            if (map.get("JCSJ") != null) {
                                long timestamp = sdf.parse(String.valueOf(map.get("JCSJ"))).getTime();
                                map.remove("JCSJ");
                                //根据站点编号查询接入编码
                                String zdbh = String.valueOf(map.get("ZDBH"));
                                map.remove("ZDBH");
                                AtmosphericStation atmosphericStation = AtmosphericStation.builder().uuid(zdbh).build();
                                List<AtmosphericStation> atmosphericStations = atmosphericStationService.selectList(atmosphericStation);
                                String host = null;
                                if (atmosphericStations.size() > 0) {
                                    host = atmosphericStations.get(0).getJrbm();
                                } else {
                                    host = zdbh;
                                }
                                MetricBuilder builder = MetricBuilder.getInstance();
                                for (Object entry : map.entrySet()) {
                                    Map.Entry<String, Object> map1 = (Map.Entry<String, Object>) entry;
                                    Double value = null;
                                    if (String.valueOf(map1.getValue()).contains(".") && String.valueOf(map1.getValue()).substring(0, String.valueOf(map1.getValue()).lastIndexOf(".")).contains(".")) {
                                        value = Double.parseDouble(String.valueOf(map1.getValue()).substring(0, String.valueOf(map1.getValue()).lastIndexOf(".")));
                                    } else {
                                        value = Double.parseDouble(String.valueOf(map1.getValue()));
                                    }
                                    builder.addMetric("mete.air").setDataPoint(timestamp, value).addTag("host", "Day" + host).addTag("index", map1.getKey().toLowerCase());
                                }
                                //存入opentsdb
                                Response response = client.pushMetrics(builder,
                                        ExpectResponse.SUMMARY);
                                if (!response.isSuccess()) {
                                    log.info("insert opentsdb data fail!map is null!");
                                }
                            }
                        }
                    }
                    pageNum++;
                    log.info("insert ZD-data-opentsdb end");
                } else {
                    AccessData accessData = AccessData.builder().type(1).url("日数据返回数据为空" + KSSJ + "--" + JSSJ).data("空气站点").build();
                    accessDataService.insert(accessData);
                }
            } else {
                log.info(methodReturn);
                AccessData accessData = AccessData.builder().type(1).url("日数据" + methodReturn + KSSJ + "--" + JSSJ).data("空气站点").build();
                accessDataService.insert(accessData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * CS 空气城市 （每日 执行）
     */
    @Scheduled(cron = "0 28 0 */1 * ?")
    @Async
    public void getCSDateDayInsertOpentsdb() {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String JSSJ = df.format(date);

        Date dateNew = date;
        Calendar calendarNew = Calendar.getInstance();
        calendarNew.setTime(dateNew);
        calendarNew.add(Calendar.DATE, -2);
        dateNew = calendarNew.getTime();
        String KSSJ = df.format(dateNew);

        HttpClientImpl client = new HttpClientImpl("http://61.164.218.155:61242");
        try {
            //空气质量城市请求地址——省平台
            String kssj = URLEncoder.encode(KSSJ, "utf-8");
            String jssj = URLEncoder.encode(JSSJ, "utf-8");
            String url = baseUrl + "?fwxh=" + fwxhCsr + "&key=" + keyCsr + "&pagenum=" + pageNum + "&pageSize=" + pageSize + "&KSSJ=" + kssj + "&JSSJ=" + jssj;
            String methodReturn = HttpURLConnectionUtil.getMethod(url);
            if (HttpURLConnectionUtil.isJsonObject(methodReturn)) {
                JSONObject jsonObject = JSONObject.parseObject(methodReturn);
                JSONObject data = jsonObject.getJSONObject("data");
                String kqzlcsxssjDay = data.getString("KQZLCSRSJ");
                //mysql数据库 记录数据插入时间
                if (kqzlcsxssjDay != null && !kqzlcsxssjDay.equals("[]")) {
                    AccessData accessData = AccessData.builder().type(2).url("日数据===>" + KSSJ + "--" + JSSJ).data("空气城市").build();
                    accessDataService.insert(accessData);
                    log.info("insert cs-opentsdb data start:");
                    //插入opentsdb
                    JSONArray jsonArray = JSONArray.parseArray(kqzlcsxssjDay);
                    for (Object o : jsonArray) {
                        Map map = JSONObject.parseObject(o.toString(), Map.class);

                        if (map.size() > 0) {
                            //移除不必要的数据
                            map.remove("PXH");
                            map.remove("BZ");
                            map.remove("CJSJ");
                            map.remove("ZDMC");
                            map.remove("XGSJ");
                            map.remove("XH");
                            map.remove("XZQHMC");

                            //空气质量指数级别
                            DateUtil.KQZLZSJBMap(map);
                            //空气质量颜色
                            DateUtil.KQZLYSMap(map);
                            //空气质量类别
                            DateUtil.KQZLLBMap(map);
                            //首要污染物
                            DateUtil.SYWRWMap(map);
                            //行政区

                            //转换时间戳
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            if (map.get("JCSJ") != null) {
                                long timestamp = sdf.parse(String.valueOf(map.get("JCSJ"))).getTime();
                                map.remove("JCSJ");
                                String host = String.valueOf(map.get("XZQHDM"));
                                map.remove("XZQHDM");
                                MetricBuilder builder = MetricBuilder.getInstance();
                                for (Object entry : map.entrySet()) {
                                    Map.Entry<String, Object> map1 = (Map.Entry<String, Object>) entry;
                                    Double value = null;
                                    if (String.valueOf(map1.getValue()).contains(".") && String.valueOf(map1.getValue()).substring(0, String.valueOf(map1.getValue()).lastIndexOf(".")).contains(".")) {
                                        value = Double.parseDouble(String.valueOf(map1.getValue()).substring(0, String.valueOf(map1.getValue()).lastIndexOf(".")));
                                    } else {
                                        value = Double.parseDouble(String.valueOf(map1.getValue()));
                                    }
                                    builder.addMetric("mete.air").setDataPoint(timestamp, value).addTag("host", "Day" + host).addTag("index", map1.getKey().toLowerCase());
                                }
                                //存入opentsdb
                                Response response = client.pushMetrics(builder,
                                        ExpectResponse.SUMMARY);
                                if (!response.isSuccess()) {
                                    log.info("insert cs-opentsdb data fail! map is null!");
                                }
                            }
                        }
                    }
                    log.info("insert cs-opentsdb data end");
                } else {
                    AccessData accessData = AccessData.builder().type(2).url("日数据返回数据为空" + KSSJ + "--" + JSSJ).data("空气城市").build();
                    accessDataService.insert(accessData);
                    log.info("返回数据为空");
                }
            } else {
                log.info(methodReturn);
                AccessData accessData = AccessData.builder().type(2).url(methodReturn + KSSJ + "--" + JSSJ).data("空气城市").build();
                accessDataService.insert(accessData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * QX 清新空气日数据
     */
    @Scheduled(cron = "0 0 1 */1 * ?")
    @Async
    public void getQXDateOpentsdb() {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String JSSJ = df.format(date);

        Date dateNew = date;
        Calendar calendarNew = Calendar.getInstance();
        calendarNew.setTime(dateNew);
        calendarNew.add(Calendar.DATE, -2);
        dateNew = calendarNew.getTime();
        String KSSJ = df.format(dateNew);

        HttpClientImpl client = new HttpClientImpl("http://61.164.218.155:61242");
        //清新空气站点请求地址——省平台
        try {
            String kssj = URLEncoder.encode(KSSJ, "utf-8");
            String jssj = URLEncoder.encode(JSSJ, "utf-8");
            String url = baseUrl + "?fwxh=" + fwxhQxr + "&key=" + keyQxr + "&pagenum=" + pageNum + "&pageSize=" + pageSize + "&KSSJ=" + kssj + "&JSSJ=" + jssj;
            String methodReturn = HttpURLConnectionUtil.getMethod(url);
            if (HttpURLConnectionUtil.isJsonObject(methodReturn)) {
                JSONObject jsonObject = JSONObject.parseObject(methodReturn);
                JSONObject data = jsonObject.getJSONObject("data");
                String qxkqzdxssjDay = data.getString("QXKQZDRSJ");

                if (qxkqzdxssjDay != null && !qxkqzdxssjDay.equals("[]")) {
                    log.info("insert qx-opentsdb data start:");
                    //mysql数据库 记录数据插入时间
                    AccessData accessData = AccessData.builder().type(3).url("日数据===>" + KSSJ + "--" + JSSJ).data("清新空气").build();
                    accessDataService.insert(accessData);
                    //插入opentsdb
                    JSONArray jsonArray = JSONArray.parseArray(qxkqzdxssjDay);
                    for (Object o : jsonArray) {
                        Map map = JSONObject.parseObject(o.toString(), Map.class);
                        if (map.size() > 0) {
                            //移除不必要的数据
                            map.remove("CJSJ");
                            map.remove("XGSJ");
                            map.remove("XH");
                            map.remove("BZ");
                            map.remove("PXH");
                            //数据标记
                            DateUtil.SJBJMap(map);

                            String yzbh = String.valueOf(map.get("YZBH"));
                            map.remove("YZBH");
                            //转换时间戳
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            if (map.get("JCSJ") != null) {
                                long timestamp = sdf.parse(String.valueOf(map.get("JCSJ"))).getTime();
                                String host = String.valueOf(map.get("ZDBH"));
                                MetricBuilder builder = MetricBuilder.getInstance();
                                map.remove("JCSJ");
                                map.remove("ZDBH");
                                for (Object entry : map.entrySet()) {
                                    Map.Entry<String, Object> map1 = (Map.Entry<String, Object>) entry;
                                    Double value = null;
                                    if ("--".equals(map1.getValue()) || StringUtils.isEmpty((String) map1.getValue())) {
                                        value = 0.0;
                                    } else {
                                        value = Double.parseDouble(String.valueOf(map1.getValue()));
                                    }
                                    builder.addMetric("mete.air").setDataPoint(timestamp, value).addTag("yzbh", yzbh)
                                            .addTag("host", "Day" + host).addTag("index", map1.getKey().toLowerCase());
                                }
                                //存入opentsdb
                                Response response = client.pushMetrics(builder,
                                        ExpectResponse.SUMMARY);
                                if (!response.isSuccess()) {
                                    log.info("insertopentsdb data fail! map is null!");
                                }
                            }
                        }
                    }
                    log.info("insert qx-opentsdb data end");
                } else {
                    log.info("返回数据为空");
                    AccessData accessData = AccessData.builder().type(3).url("日数据返回为空" + KSSJ + "--" + JSSJ).data("清新空气").build();
                    accessDataService.insert(accessData);
                }
            } else {
                log.info(methodReturn);
                AccessData accessData = AccessData.builder().type(3).url(methodReturn + KSSJ + "--" + JSSJ).data("清新空气").build();
                accessDataService.insert(accessData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * Town 大气乡镇 (每 日 执行)
     */
    @Scheduled(cron = "0 31 1 */1 * ?")
    @Async
    public void getTownDayInsertOpentsdb() {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String JSSJ = df.format(date);

        Date dateNew = date;
        Calendar calendarNew = Calendar.getInstance();
        calendarNew.setTime(dateNew);
        calendarNew.add(Calendar.DATE, -2);
        dateNew = calendarNew.getTime();
        String KSSJ = df.format(dateNew);

        HttpClientImpl client = new HttpClientImpl("http://61.164.218.155:61242");
        try {
            String type = URLEncoder.encode("日均值", "utf-8");
            String startTime = URLEncoder.encode(KSSJ, "utf-8");
            String endTime = URLEncoder.encode(JSSJ, "utf-8");
            String url = getDataQTownByxzqh + "?type=" + type + "&startTime=" + startTime + "&endTime=" + endTime;
            String methodReturn = HttpURLConnectionUtil.getMethod(url);
            if (null != methodReturn && !"[]".equals(methodReturn)) {
                //mysql数据库 记录数据插入时间
                AccessData accessData = AccessData.builder().type(6).url("日数据===>" + KSSJ + "--" + JSSJ).data("大气乡镇").build();
                accessDataService.insert(accessData);
                JSONArray jsonArray = JSONArray.parseArray(methodReturn);
                for (Object o : jsonArray) {
                    Map map = JSONObject.parseObject(o.toString(), Map.class);
                    if (map.size() > 0) {
                        //转换时间戳
                        String jcsj = (String) map.get("JCSJ");
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        long timestamp = sdf.parse(jcsj).getTime();
                        //根据站点名称获取设备ID
                        String zdmc = (String) map.get("ZDMC");
                        String host = townAtmosphericStationService.selectZDBH(zdmc);
                        map.remove("JCSJ");
                        map.remove("ZDMC");
                        MetricBuilder builder = MetricBuilder.getInstance();
                        for (Object entry : map.entrySet()) {
                            Map.Entry<String, Integer> map1 = (Map.Entry<String, Integer>) entry;
                            Integer value = map1.getValue();
                            builder.addMetric("mete.atmospheric").setDataPoint(timestamp, value).addTag("host", "Day" + host).addTag("index", map1.getKey().toLowerCase());
                        }
                        //存入opentsdb
                        Response response = client.pushMetrics(builder,
                                ExpectResponse.SUMMARY);
                        if (!response.isSuccess()) {
                            log.info("town data insert fail---map is null！");
                        }
                    }
                }
            }else {
                AccessData accessData = AccessData.builder().type(6).url("日数据为空===>" + KSSJ + "--" + JSSJ).data("大气乡镇").build();
                accessDataService.insert(accessData);
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
